import os

from django.http import HttpResponseRedirect
from django.shortcuts import render,redirect
from loguru import logger
from .models import Website, Rad
from apps.staruser.models import LoginHistory
from ..prescription.models import Prescription


# Create your views here.

def welcome(request):
    context = {}
    return render(request, 'welcome.html', context)

def index(request):
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/login')
    else:
        loginhistory = LoginHistory.objects.filter(user__id=user_id,loginstatus=True).order_by("-id")
        if loginhistory:
            login_obj = loginhistory[0]
            log_num = login_obj.username if login_obj else ""
            loginnum = login_obj.loginnum if login_obj.loginnum else ""
            LoginHistory.objects.filter(user_id=user_id,loginstatus=True).exclude(pk=login_obj.pk).update(loginstatus=False)
        else:
            return HttpResponseRedirect('/login')

    website_obj = Website.objects.filter(is_delete=False,is_active=True)
    if not website_obj:
        logger.debug("未维护网站信息请检查是否已删除或禁用")
        return HttpResponseRedirect('/login')

    context = {
        'title': website_obj[0].name,
        'btn_1': website_obj[0].btn_1,
        'btn_2': website_obj[0].btn_2,
        'btn_3': website_obj[0].btn_3,
        'apiurl': website_obj[0].apiurl,
        'login_id':id,
        'loginnum':loginnum,
        'log_num':log_num
    }

    return render(request, 'index.html', context)

def buy_med(request):
    context = {

    }
    return render(request,'userinfo.html',context)

def peisong(request):
    context = {}
    return render(request, 'peisong.html', context)



def self_prescrip(request):
    context = {}
    return render(request, 'self_prescrip.html', context)


def rad(request):
    context = {}
    return render(request, 'Rad/new_order.html', context)


def Order(request):
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')
    rad = Rad.objects.filter(is_delete=False,is_active=True)

    prescription = Prescription.objects.filter(is_delete=False,OrderStatus="0",user__id=user_id)

    context = {
        "prescription_list": prescription,
        "user_id": user_id,
        "rad_list": rad
    }
    return render(request, 'Order/new_order.html', context)


def userinfo(request):
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')
    context = {
        "user_id": user_id
    }
    return render(request, os.path.join('user','userinfo.html'),context)


def changepwd(request):
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')
    context = {
        "user_id": user_id
    }
    return render(request, os.path.join('user','changepwd.html'),context)
